# rubocop:disable Naming/MethodName
module DengHaiLightTools
  module Tools
    class CopyLight
      def initialize
        @mouse_ip = Sketchup::InputPoint.new
        @pick_point = 0
      end

      def activate
        @previous_tool = Sketchup.active_model.tools.active_tool # 保存当前使用的工具
        Sketchup.status_text = '在X轴按【物体原点】对称复制。'
        @selection = Sketchup.active_model.selection
        nil unless @selection.empty?
      end

      def onMouseMove(_flags, x, y, view)
        @mouse_ip.pick(view, x, y)
        view.invalidate
      end

      def onKeyDown(key, _repeat, _flags, _view)
        # return unless key == 17
      end

      def onLButtonDown(_flags, _x, _y, view)
        @pick_point = @mouse_ip.position.x
        if do_copy < 1
          UI.messagebox('未复制任何灯具！')
          Sketchup.active_model.select_tool(nil)
        end
        view.invalidate
      end

      def deactivate(view)
        # 当工具停用时清除箭头
        view.invalidate
      end

      # `onSetCursor` 会频繁调用，因此在此处不应该做太多的工作。
      def onSetCursor
        UI.set_cursor(UI.create_cursor("#{ICON_PATH}/mouse_copy_light.png", 0, 0))
      end

      def draw(view)
        @mouse_ip.draw(view)
      end

      def do_copy
        edit_number = 0
        @selection.each do |obj|
          next unless DengHaiLightTools.helpers_get_attribute(obj)

          edit_number += 1
          new_obj = obj.copy

          new_obj.add_observer(DontEditIt.new)
          DengHaiLightTools.helpers_copy_attribute(obj, new_obj)
          obj_x = new_obj.transformation.origin.x
          move_number = (@pick_point - obj_x) * 2
          move_transformation = Geom::Transformation.new([move_number, 0, 0])
          new_obj.transform!(move_transformation)

          # 获取原物体的旋转角度
          original_rotation_matrix = obj.transformation.to_a[0..2]
          original_angle_z = Math.atan2(original_rotation_matrix[1], original_rotation_matrix[0]).radians # 原来的旋转角度

          # 创建旋转变换
          rotation_point = new_obj.transformation.origin # 原点位置
          new_angle = - (original_angle_z.degrees * 2)
          rotation = Geom::Transformation.rotation(rotation_point, Z_AXIS, new_angle)
          new_obj.transform!(rotation)
          Sketchup.active_model.select_tool(nil)
        end
        edit_number
      end
    end
  end
end
# rubocop:enable Naming/MethodName
